package controllers;

import play.mvc.*;

import com.fasterxml.jackson.databind.JsonNode; 

import views.html.*;
import models.*;

public class Application extends Controller {
  
	static boolean czy_pierwszy = true;
	static boolean czy_gra= false;
	static boolean czy_boty = false;
	static String human2;
	static String bot2;
	static String money2;
	static String wpisowe2;
    /**
     * Display the home page.
     */
    public static Result index() {
        if (czy_pierwszy){
        	czy_pierwszy=false;
        	return pierwszy(); 
        }
        else
    		return ok(index.render());
    }
  
    /**
     * Display the chat room.
     */
    public static Result chatRoom(String username, String human, String bot, String money, String wpisowe) {
        if(username == null || username.trim().equals("")) {
            flash("error", "Podano niepoprawną nazwe użytkownika!.");
            return redirect(routes.Application.index());
        }
        	if(!czy_gra){
        		czy_gra = true;
        		human2 = human;
        		bot2 = bot;
        		money2 = money;
        		wpisowe2 = wpisowe;
        		return ok(chatRoom.render(username, human, bot, money, wpisowe));	
        	}
        	else{
        		if(human2==null){
        			flash("error", "Gra nie została jeszcze utworzona, proszę chwilę poczekać");
                    return redirect(routes.Application.index());
        		}  			
        		else
        		return ok(chatRoom.render(username, human2, bot2, money2, wpisowe2));
        	}
    }
   
    public static Result pierwszy(){
    	return ok(pierwszy.render());
    }
    

    public static Result chatRoomJs(String username,String human, String bot, String money, String wpisowe) {
        return ok(views.js.chatRoom.render(username,human, bot, money, wpisowe));
    }
    
    /**
     * Handle the chat websocket.
     */
    public static WebSocket<JsonNode> chat(final String username, final String human, final String bot, final String money, final String wpisowe) {
        return new WebSocket<JsonNode>() {
            
            // Called when the Websocket Handshake is done.
            public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){
                int i;
                // Join the chat room.
                try { 
                    Table.join(username, in, out, human,bot,money,wpisowe);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                
                if(!czy_boty){
                	czy_boty=true;
                for(i=0;i < Integer.parseInt(bot);i++){
	                try {
						Table.botjoin("bot "+(i+1));
					} catch (Exception e) {
						e.printStackTrace();
					}
                }
                }
            }
            		
        };
    }
  
}
